package com.neusoft.EYSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neusoft.EYSystem.dao.ClientDAO;
import com.neusoft.EYSystem.dao.MealConfigDAO;
import com.neusoft.EYSystem.po.*;
import com.neusoft.EYSystem.service.MealConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MealConfigServiceImpl implements MealConfigService {
    // ✅ 工具方法：判断是否为合法字符串（排除 null、空串、"null"）
    private boolean isValid(String value) {
        return value != null && !value.trim().isEmpty() && !"null".equalsIgnoreCase(value.trim());
    }

    @Autowired
    private MealConfigDAO mealConfigDAO;
    @Autowired
    private ClientDAO clientDAO;

    @Override
    public PageResponseBean<List<ClientAndConfig>> pageClientAndConfig(Long cur, Long number, Client client) {
        List<ClientAndConfig> fullList = new ArrayList<>();

        // 1. 客户名模糊匹配查询
        QueryWrapper<Client> wrapperClient = new QueryWrapper<>();
        if (isValid(client.getName())) {
            wrapperClient.like("name", client.getName());
        }
        List<Client> clientList = clientDAO.selectList(wrapperClient);

        // 2. 根据每个 client 查询 meal_config
        for (Client c : clientList) {
            QueryWrapper<MealConfig> wrapperConfig = new QueryWrapper<>();
            wrapperConfig.eq("client_id", c.getClientId());


            List<MealConfig> configs = mealConfigDAO.selectList(wrapperConfig);
            for (MealConfig config : configs) {
                ClientAndConfig cac = new ClientAndConfig();
                cac.setClient(c);
                cac.setMealConfig(config);
                fullList.add(cac);
            }
        }

        // 3. 手动分页
        int fromIndex = (int) ((cur - 1) * number);
        int toIndex = Math.min(fromIndex + number.intValue(), fullList.size());
        List<ClientAndConfig> pageList = fromIndex < fullList.size() ? fullList.subList(fromIndex, toIndex) : List.of();

        // 4. 返回封装结构
        PageResponseBean<List<ClientAndConfig>> rb = new PageResponseBean<>(pageList);
        rb.setTotal(fullList.size());
        return rb;
    }

}
